package cn.edu.nju.ws.sview.views;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Properties;

import cn.edu.nju.ws.sview.database.DBConnectionFactory;
import cn.edu.nju.ws.sview.views.DataMember.DataMemberItem;

class NewComparator implements Comparator<DataMemberItem>{
	private HashMap<DataMemberItem, Integer> map;
	NewComparator(HashMap<DataMemberItem, Integer> m){
		map = m;
	}
	@Override
	public int compare(DataMemberItem d0, DataMemberItem d1) {
		// TODO Auto-generated method stub
		int c0 = map.get(d0), c1 = map.get(d1);
		if(c0 < c1)
			return 1;
		if(c0 > c1)
			return -1;
		return 0;
	}
	
}
class NewComparator2 implements Comparator<Integer>{
	private HashMap<Integer, Integer> map;
	NewComparator2(HashMap<Integer, Integer> m){
		map = m;
	}
	@Override
	public int compare(Integer d0, Integer d1) {
		// TODO Auto-generated method stub
		int c0 = map.get(d0), c1 = map.get(d1);
		if(c0 < c1)
			return 1;
		if(c0 > c1)
			return -1;
		return 0;
	}
	
}

public class Filter {
//	filter_op_equal=1
//	filter_op_class=2
//	filter_op_notlessthan=3
//	filter_op_notlargethan=4
    public static final int OP_EQUAL;
    public static final int OP_CLASS;
    public static final int OP_NOTLESSTHAN;
    public static final int OP_NOTLARGERTHAN;
	private int dmtype;
	private int dmid;
	private int op;
    static{
      	 Properties properties = new Properties();
      	 try {
   			properties.load(View.class.getClassLoader().getResourceAsStream("conf.properties")) ;
   		} catch (IOException e) {
   			// TODO Auto-generated catch block
   			e.printStackTrace();
   		}
   		OP_EQUAL = Integer.parseInt(properties.getProperty("filter_op_equal"));
   		OP_CLASS = Integer.parseInt(properties.getProperty("filter_op_class"));
   		OP_NOTLESSTHAN = Integer.parseInt(properties.getProperty("filter_op_notlessthan"));
   		OP_NOTLARGERTHAN = Integer.parseInt(properties.getProperty("filter_op_notlargethan"));
   		properties.clear();
    }
    
   
    public Filter(int dmtype,int dmid,int op){
    	this.dmtype= dmtype;
    	this.dmid = dmid;
    	this.op = op;
    }
    
    /**
     * 通过filter访问最近时间内访问次数进行推荐
     * @param classes.类的集合
     * @param userId 当前登录用户的id 若未登录，则传入-1
     * @return
     */
    public static ArrayList<Filter> getRecmdFiltersByPopularity(HashSet<Integer> classes, int userId, int requiredNum){
    	String sql = "";
    	if(userId == -1){
    		sql = "SELECT SUM(times_recent) FROM user_day_filter WHERE filter_id = ?;"; 
    	}
    	else{
    		sql = "SELECT SUM(times_recent) FROM user_day_filter WHERE filter_id = ? AND user_id = " + userId + ";";
    	}
    	ArrayList<Filter> ret = new ArrayList<Filter>(requiredNum);
    	ArrayList<Integer> temp = new ArrayList<Integer>(requiredNum);
    	HashMap<Integer, Integer> counts = new HashMap<Integer, Integer>();
    	int count = 0;
    	PreparedStatement ps;
    	Connection conn = DBConnectionFactory.getConnection();
    	for(int cl : classes){
    		counts.put(cl, 0);
    		try {
				ps = conn.prepareStatement(sql);
				ps.setInt(1, cl);
				ResultSet rs = ps.executeQuery();
				boolean find = false;
				while(rs.next()){
					int times = rs.getInt("SUM(times_recent)");
					counts.put(cl, counts.get(cl) + times);
					find = true;
				}
				if(find){
					count++;
					temp.add(cl);
					if(count == requiredNum)
						break;
				}
				rs.close();
				ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		
    	}
    	if(userId != -1 && count < requiredNum){
    		sql = "SELECT SUM(times_recent) FROM user_day_filter WHERE filter_id = ?;";
    		for(int cl : classes){
    			if(temp.contains(cl))
    				continue;
        		counts.put(cl, 0);
        		try {
    				ps = conn.prepareStatement(sql);
    				ps.setInt(1, cl);
    				ResultSet rs = ps.executeQuery();
    				boolean find = false;
    				while(rs.next()){
    					int times = rs.getInt("SUM(times_recent)");
    					counts.put(cl, counts.get(cl) + times);
    					find = true;
    				}
    				if(find){
    					count++;
    					temp.add(cl);
    					if(count == requiredNum)
    						break;
    				}
    				rs.close();
    				ps.close();
    			} catch (SQLException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
        	}
    	}
    	try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	Collections.sort(temp, new NewComparator2(counts));
    	sql = "SELECT dm_id, dm_type, op FROM filter WHERE id = ?;";
    	conn = DBConnectionFactory.getConnection();
    	for(int fid : temp){
    		try {
				ps = conn.prepareStatement(sql);
				ps.setInt(1, fid);
				ResultSet   rs = ps.executeQuery();
				while(rs.next()){
					int memberId = rs.getInt("dm_id");
					int memberType = rs.getInt("dm_type");
					int op = rs.getInt("op");
					ret.add(new Filter(memberType, memberId, op));
				}
				ps.close();
	    		rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	try {
    		conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return ret;
    }
    
    /**
     * 根据用户filter使用的
     * @param classes.类的集合
     * @return
     */
    public static ArrayList<Filter> getRecmdFiltersByLogs(HashSet<Integer> classes){
    	
    	return null;
    }
    
    /**
     * 将输入的 datamember根据最近M天使用的次数进行排序
     * @param datamembers.可用的datammeber集合.第一个元素:dmtype ,第二个元素dmid
     * @return. 对于输入的集合排序
     */
    public static ArrayList<DataMemberItem> sortByPopularity(HashSet<DataMemberItem> datamembers){
    	String sql = "SELECT SUM(times_recent) FROM dmInCollection_day_visit WHERE member_id = ? AND member_type = ?";
    	ArrayList<DataMemberItem> ret = new ArrayList<DataMemberItem>(datamembers);
    	HashMap<DataMemberItem, Integer> counts = new HashMap<DataMemberItem, Integer>();
    	Connection conn = DBConnectionFactory.getConnection();
    	for(DataMemberItem dm : datamembers){
    		counts.put(dm, 0);
    		PreparedStatement ps;
    		try{
    			ps = conn.prepareStatement(sql);
    			ps.setInt(1, dm.dmid);
    			ps.setInt(2, dm.dmtype);
    			ResultSet rs = ps.executeQuery();
    			while(rs.next()){
    				int times = rs.getInt("SUM(times_recent)");
    				counts.put(dm, counts.get(dm) + times);
    			}
    			rs.close();
    			ps.close();
    		}catch(SQLException e){
    			e.printStackTrace();
    		}
    	}
    	try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	Collections.sort(ret, new NewComparator(counts));
    	return ret;
    }
    public static void main(String[] args){
    	/*
    	HashSet<DataMemberItem> t = new HashSet<DataMemberItem>();
    	t.add(new DataMemberItem(1, 1, false));
    	t.add(new DataMemberItem(1, 2, false));
    	t.add(new DataMemberItem(1, 3, false));
    	t.add(new DataMemberItem(1, 4, false));
    	ArrayList<DataMemberItem> r = sortByPopularity(t);
    	for(DataMemberItem i : r){
    		System.out.println(i.dmid);
    	}*/
    	HashSet<Integer> t = new HashSet<Integer>();
    	t.add(1);t.add(2); t.add(3); t.add(4);
    	ArrayList<Filter> res = Filter.getRecmdFiltersByPopularity(t, 2, 4);
    	for(Filter f : res){
    		System.out.println(f.dmid + " " + f.dmtype + " " + f.op);
    	}
    }
    	
}

